package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author:YZN
 * @date:2022/12/21
 * @description:
 */
@Api(tags = "员工登录")
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private HttpServletRequest request;

    /**
     * 登录功能
     * @param employee
     * @return
     */
    @ApiOperation(value = "员工登录请求")
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee) {
        R<Employee> result = employeeService.login(employee);
        //判断登录成功后 将Id存入到session中
        if (result.getCode() == 1) {
            request.getSession().setAttribute("employee", result.getData().getId());
        }
        return result;
    }

    /**
     * 退出功能
     */
    @ApiOperation("员工登出请求")
    @PostMapping("/logout")
    public R logout(){
        //清空该用户的session就等于退出
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    /**
     * 新增员工
     * @param employee
     * @return
     */
    @ApiOperation("新增员工")
    @PostMapping
    public R add(@RequestBody Employee employee){
        employeeService.add(employee);
        return R.success("新增成功");
    }

    /**
     * 员工账号分页和条件查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R page(@RequestParam(name = "page",defaultValue = "1")Integer page,
                  @RequestParam(name = "pageSize",defaultValue = "5")Integer pageSize,
                  @RequestParam(name = "name",required = false)String name){

        return employeeService.page(page,pageSize,name);
    }

    /**
     * 员工账号启用 or 禁用 ||员工的修改
     * @param employee
     * @return
     */
    @PutMapping
    public R update(@RequestBody Employee employee){
        return employeeService.modify(employee);
    }

    /**
     * 编辑时 数据回显
     */
    @GetMapping("/{id}")
    public R findById(@PathVariable("id") Long id){

        return employeeService.findById(id);
    }
}
